import redis
import socket
import sys
from datetime import datetime

# 配置 Redis 哨兵连接信息和主节点名称
REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
REDIS_PASSWORD = "123456"

# 配置 Nginx 监听地址和端口
NGINX_HOST = "127.0.0.1"
NGINX_PORT = 9088

log_info_file = open('/proc/1/fd/1', 'w')
log_error_file = open('/proc/1/fd/2', 'w')

def check_nginx():
    try:
        # 尝试连接到 Nginx
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2)
        result = sock.connect_ex((NGINX_HOST, NGINX_PORT))
        sock.close()
        return result == 0
    except Exception as e:
        print(f"{datetime.now()}==检查 Nginx 状态出错: {e}", file=log_error_file)
        return False

def check_redis_master():
    try:
        # 尝试连接到 Redis 主节点
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2)
        result = sock.connect_ex((REDIS_HOST, REDIS_PORT))
        sock.close()
        return result == 0
    except Exception as e:
        print(f"{datetime.now()}==检查 Redis 主节点状态出错: {e}", file=log_error_file)
        return False



if __name__ == "__main__":
  if not check_nginx() or not check_redis_master():
    sys.exit(1)  # 只要有一个服务状态异常，脚本返回失败退出码
  else:
    sys.exit(0)  # 两个服务状态都正常，脚本返回成功退出码